#include <memory>
#include "EpollServer.hpp"

Response CalculatorHelp(Request req)
{
    Response resp;
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;

        break;
    case '*':
        resp._result = req._x * req._y;

        break;
    case '/':
        if(req._y == 0)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;
    case '%':
        if(req._y == 0)
            resp._code = 0;
        else
            resp._result = req._x % req._y;
        break;
    default:
        resp._code = 2;
    }
    return resp;
}
void Calculator(Connection* conn,Request req)
{
    // 1. 业务处理，得到响应
    Response res = CalculatorHelp(req);
    std::string resStr;
    // 2. 将响应序列化
    res.Serialize(&resStr);
    // 3. 添加报头
    resStr = addHeaders(resStr);
    // 4. 加入输出缓冲区中
    conn->_outbuf += resStr;
    // 5. 写开关是按需设置的，此时就能将写开关打开。
    conn->_thisEpoll->EnableReadWrite(conn,true,true);
    std::cout << "Calulator success..." << std::endl;
}

int main()
{
    std::unique_ptr<EpollServer> svr(new EpollServer(Calculator));   
    svr->InitServer();
    svr->Dispatcher();
    return 0;
}